import { reqCartList ,reqDeleteCartById,reqUpdateCheckedById} from "@/api";
const state = {
    cartList:[],
};
const actions = {
    async getCartList({ commit }) {
        let result = await reqCartList();
        if (result.code == 200) {
            commit('GETCARTLIST', result.data);
        }
        else {
            console.log("请求购物车列表失败");
        }
    },
    async deleteCartListBySkuId({ commit }, skuId) {
        let res = await reqDeleteCartById(skuId);
        console.log(skuId)
        if (res.code == 200) {
            return 'ok'
        }
        else {
            return new Promise(new Error('faile'));
        }
    },
    //修改购物车选中状态
    async updateCheckedById({ commit }, { skuId, isChecked }) {
        let res = await reqUpdateCheckedById(skuId, isChecked); 
        if (res.code != 200)
            console.log("修改选中失败");
        else console.log(skuId + "==" + isChecked);
    },
    //注意一次调用多个接口必须要promise数组，否则修改不同步
    deleteAllCheckedcart({ dispatch, state }) {
        let promiseAll = [];
        state.cartList.forEach(element => {
            if (element.isChecked == 1) {
               let p = dispatch('deleteCartListBySkuId',element.skuId);
                promiseAll.push(p);
            }
        });
        return Promise.all(promiseAll);
    },
    //全改全部产品的选中状态
    // *****************注意如果同时需要发送多个请求时需要用到promise数组
    isCheckedAll({ dispatch, state }, isChecked) {
        let promiseAll = [];
        state.cartList.forEach(element => {
            let p = dispatch('updateCheckedById', { skuId: element.skuId, isChecked });
            promiseAll.push(p);
        });
        return Promise.all(promiseAll);
    },
};
const mutations = {
    GETCARTLIST(state, data) {
        if (data[0] == undefined) state.cartList = [];
        else state.cartList = data[0].cartInfoList;
    }
};
const getters = {};

export default {
    state,
    actions,
    mutations,
    getters
}